package com.ruoyi.web.controller.system;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.system.SysCityInfo;
import com.ruoyi.common.core.domain.entity.system.SysScenic;
import com.ruoyi.common.core.domain.model.OperationTimeAndSwitchModeBody;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.exception.job.TaskException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.service.ISysCityInfoService;
import com.ruoyi.system.service.ISysScenicService;
import com.ruoyi.system.service.ISysWharfService;
import lombok.Data;
import org.apache.commons.lang3.ArrayUtils;
import org.quartz.SchedulerException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 景区信息Controller
 *
 * @author ruoyi
 * @date 2023-05-04
 */
@RestController
@RequestMapping("/system/scenic")
public class SysScenicController extends BaseController {
    @Autowired
    private ISysScenicService sysScenicService;

    @Autowired
    private ISysWharfService sysWharfService;

    @Autowired
    private ISysCityInfoService cityInfoService;

    @Data
    public static class SysScenicVo {
        /**
         * 景区ID
         */
        private Long scenicId;

        /**
         * 父景区ID
         */
        private Long parentId;

        /**
         * 景区名称
         */
        private String scenicName;

        /**
         * 景区简称
         */
        private String scenicShortName;

        /**
         * 景区所在城市
         */
        private String city;

        /**
         * 景区详细地址
         */
        private String address;

        /**
         * 景区负责人
         */
        private String leader;

        /**
         * 负责人电话
         */
        private String phone;

        /**
         * 负责人邮箱
         */
        private String email;

        /**
         * 景区启用状态 (0：正常 1：已停用)
         */
        private String status;
        /**
         * 码头的字母序号，char类型，示例：A，B，C, …等。
         */
        private String wharfCode;
        /**
         * 景区默认码头的名称。
         */
        private String wharfName;
        /**
         * 景区默认码头的纬度。
         */
        private Double wharfLat;
        /**
         * 景区默认码头的经度。
         */
        private Double wharfLng;
        /**
         * 景区默认码头的泊位朝向，即船头朝向与正北方向的夹角，范围0~360°。
         */
        private Integer heading;
        /**
         * 景区默认码头对应的电子围栏两固定点之间的直线距离，单位：米。
         */
        private Integer toFixedPointsDistance;
        /**
         * 景区默认码头对应的电子围栏两固定点的真实gps坐标。
         */
        private String toFixedPointsCoordinates;
        /**
         * 景区默认码头对应的电子围栏两固定点的百度地图坐标。
         */
        private String toFixedPointsBdCoordinates;
    }

    /**
     * 查询景区信息列表
     */
    @PreAuthorize("@ss.hasPermi('system:scenic:list')")
    @GetMapping("/list")
    public AjaxResult list(SysScenic sysScenic) {
        List<SysScenic> list = sysScenicService.selectSysScenicList(sysScenic);
        //过滤掉全国景区与无疆景区
        List<SysScenic> scenics = list.stream().filter(scenic -> scenic.getScenicId() != 100 && scenic.getScenicId() != 101)
                .collect(Collectors.toList());
        return success(scenics);
    }

    /**
     * 查询部门列表（排除节点）
     */
    @PreAuthorize("@ss.hasPermi('system:scenic:list')")
    @GetMapping("/list/exclude/{scenicId}")
    public AjaxResult excludeChild(@PathVariable(value = "scenicId", required = false) Long scenicId) {
        //查询出所有景区
        List<SysScenic> sysScenics = sysScenicService.selectSysScenicList(new SysScenic());
        sysScenics.removeIf(s -> s.getScenicId().intValue() == scenicId ||
                ArrayUtils.contains(StringUtils.split(s.getAncestors(), ","), scenicId + ""));
        return success(sysScenics);
    }

    /**
     * 导出景区信息列表
     */
    @PreAuthorize("@ss.hasPermi('system:scenic:export')")
    @Log(title = "景区信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysScenic sysScenic) {
        List<SysScenic> list = sysScenicService.selectSysScenicList(sysScenic);
        ExcelUtil<SysScenic> util = new ExcelUtil<SysScenic>(SysScenic.class);
        util.exportExcel(response, list, "景区信息数据");
    }

    /**
     * 获取景区信息详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:scenic:query')")
    @GetMapping(value = "/{scenicId}")
    public AjaxResult getInfo(@PathVariable("scenicId") Long scenicId) {
        return success(sysScenicService.selectSysScenicByScenicId(scenicId));
    }

    /**
     * 新增景区信息
     */
    @PreAuthorize("@ss.hasPermi('system:scenic:add')")
    @Log(title = "景区信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody SysScenicVo sysScenicVo) {
        SysScenic sysScenic = new SysScenic();
        BeanUtils.copyProperties(sysScenicVo, sysScenic);
        if (UserConstants.NOT_UNIQUE.equals(sysScenicService.checkScenicNameUnique(sysScenic))) {
            return error("新增景区'" + sysScenic.getScenicName() + "'失败，景区名称已存在");
        }

        String city = sysScenicVo.getCity();
        if (StringUtils.isNotEmpty(city)) {
            List<SysCityInfo> cityInfoList = cityInfoService.getCityInfoByCityName(city);
            if (Objects.nonNull(cityInfoList) && cityInfoList.size() > 0) {
                SysCityInfo firstCityInfo = cityInfoList.get(0);
                sysScenic.setCityAreaCode(firstCityInfo.getAreaCode());
            }
        }

        sysScenic.setCreateBy(getUsername());
        sysScenic.setCreateTime(DateUtils.getNowDate());
        int insertNum = sysScenicService.insertSysScenic(sysScenic);

//        if (insertNum > 0) {
//            SysWharf sysWharf = new SysWharf();
//            sysWharf.setScenicId(sysScenic.getScenicId());
//            sysWharf.setWharfCode(sysScenicVo.getWharfCode());
//            sysWharf.setWharfName(sysScenicVo.getWharfName());
//            sysWharf.setLat(new BigDecimal(sysScenicVo.getWharfLat()));
//            sysWharf.setLon(new BigDecimal(sysScenicVo.getWharfLng()));
//            sysWharf.setHeading(sysScenicVo.getHeading());
//            sysWharf.setToFixedPointsDistance(sysScenicVo.getToFixedPointsDistance());
//            sysWharf.setToFixedPointsCoordinates(sysScenicVo.getToFixedPointsCoordinates());
//            sysWharf.setToFixedPointsBdCoordinates(sysWharf.getToFixedPointsBdCoordinates());
//            sysWharf.setCreateBy(getUsername());
//            sysWharfService.insertWharf(sysWharf);
//        }

        return toAjax(insertNum);
    }

    /**
     * 修改景区信息
     */
    @PreAuthorize("@ss.hasPermi('system:scenic:edit')")
    @Log(title = "景区信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SysScenic sysScenic) {
        Long scenicId = sysScenic.getScenicId();
        if (UserConstants.NOT_UNIQUE.equals(sysScenicService.checkScenicNameUnique(sysScenic))) {
            return error("修改景区'" + sysScenic.getScenicName() + "'失败，景区名称已存在");
        } else if (Objects.nonNull(sysScenic.getParentId()) && sysScenic.getParentId().equals(scenicId)) {
            return error("修改景区'" + sysScenic.getScenicName() + "'失败，上级景区不能是自己");
        }

        String city = sysScenic.getCity();
        if (StringUtils.isNotEmpty(city)) {
            List<SysCityInfo> cityInfoList = cityInfoService.getCityInfoByCityName(city);
            if (Objects.nonNull(cityInfoList) && cityInfoList.size() > 0) {
                SysCityInfo firstCityInfo = cityInfoList.get(0);
                sysScenic.setCityAreaCode(firstCityInfo.getAreaCode());
            }
        }

        sysScenic.setUpdateBy(getUsername());
        sysScenic.setUpdateTime(DateUtils.getNowDate());
        return toAjax(sysScenicService.updateSysScenic(sysScenic));
    }

    /**
     * 修改景区运营状态信息
     */
    @PreAuthorize("@ss.hasPermi('system:scenic:edit')")
    @Log(title = "景区信息", businessType = BusinessType.UPDATE)
    @PutMapping("/changeOperationStatus")
    public AjaxResult changeOperationStatus(@RequestBody SysScenic sysScenic) {
        sysScenic.setUpdateBy(getUsername());
        sysScenic.setUpdateTime(DateUtils.getNowDate());
        return toAjax(sysScenicService.updateSysScenic(sysScenic));
    }

    /**
     * 删除景区信息
     */
//    @PreAuthorize("@ss.hasPermi('system:scenic:remove')")
//    @Log(title = "景区信息", businessType = BusinessType.DELETE)
//    @DeleteMapping("/{scenicIds}")
//    public AjaxResult remove(@PathVariable Long[] scenicIds) {
//        return toAjax(sysScenicService.deleteSysScenicByScenicIds(scenicIds));
//    }


    /**
     * 更新景区的运营时间及运营状态切换模式。
     *
     * @param dataBody
     * @return
     * @throws SchedulerException
     * @throws TaskException
     */
    @PreAuthorize("@ss.hasPermi('system:scenic:edit')")
    @Log(title = "景区信息", businessType = BusinessType.UPDATE)
    @PutMapping("/updateOperationTimeAndSwitchMode")
    public AjaxResult updateOperationTimeAndSwitchMode(@RequestBody OperationTimeAndSwitchModeBody dataBody) throws SchedulerException, TaskException {
        sysScenicService.updateOperationTimeAndSwitchMode(dataBody);
        return success();
    }

    /**
     * 根据id删除景区
     */
    @PreAuthorize("@ss.hasPermi('system:dept:remove')")
    @Log(title = "部门管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{scenicId}")
    public AjaxResult remove(@PathVariable Long scenicId) {
        SysScenic sysScenic = sysScenicService.selectSysScenicByScenicId(scenicId);
        if (Objects.isNull(sysScenic)) {
            return warn("没找到对应景区，删除失败！");
        }

        if (sysScenicService.hasChildByScenicId(scenicId)) {
            return warn("存在下级景区,不允许删除");
        }

        //删除当前景区名下的所有码头
//        SysWharf sysWharf = new SysWharf();
//        sysWharf.setScenicId(sysScenic.getScenicId());
//        List<SysWharf> sysWharfList = sysWharfService.selectWharfList(sysWharf);
//        sysWharfList.forEach(wharf -> {
//            sysWharfService.deleteWharfByWharfId(wharf.getWharfId());
//        });

        return toAjax(sysScenicService.deleteSysScenicByScenicId(scenicId));
    }
}
